<?php
/**
 * A simple description for this script
 *
 * PHP Version 5.2.0 or Upper version
 *
 * @package    Iris
 * @author     Hidehito NOZAWA aka Suin <http://suin.asia>
 * @copyright  2010 Hidehito NOZAWA
 * @license    http://www.gnu.org/licenses/gpl-2.0.html GNU GPL v2
 *
 */

class Iris_Class_Criteria
{
	protected $criteria = array();
	protected $andor    = 'AND';

	protected $operators = array(
		'=', '>', '>=', '<', '<=', '!=', '^=', '$=', '*=', 'IN', 'NOT IN',
	);

	public function __construct($andor = null)
	{
		if ( $andor === 'OR' )
		{
			$this->andor = 'OR';
		}
		else
		{
			$this->andor = 'AND';
		}
	}

    public function __toString()
    {
        return $this->render();
    }

	public function add($param1, $param2 = null, $param3 = null)
	{
		if ( is_object($param1) and is_a($param1, 'Iris_Class_Criteria') )
		{
			$this->criteria[] = $param1;
			return;
		}
		elseif ( !in_array($param2, $this->operators, true) and $param3 === null )
		{
			$name     = $param1;
			$value    = $param2;
			$operator = reset($this->operators);
		}
		elseif ( in_array($param2, $this->operators, true) and $param3 !== null )
		{
			$name     = $param1;
			$value    = $param3;
			$operator = $param2;
		}

		$this->criteria[] = array($name, $value, $operator);
	}

	public function render()
	{
		$conditions = array();
		$likes = array('^=', '$=', '*=');

		foreach ( $this->criteria as $criterion )
		{
			if ( is_object($criterion) )
			{
				if ( is_a($criterion, 'Iris_Class_Criteria') )
				{
					$conditions[] = '( '.$criterion->render().' )';
					continue;
				}
			}

			list($name, $value, $operator) = $criterion;

			$prefix  = '';
			$postfix = '';

			if ( $operator === '*=' )
			{
				$prefix  = '%';
				$postfix = '%';
			}
			elseif ( $operator == '^=' )
			{
				$prefix  = '';
				$postfix = '%';
			}
			elseif ( $operator == '$=' )
			{
				$prefix  = '%';
				$postfix = '';
			}

			$prefix  = "'".$prefix;
			$postfix = $postfix."'";

			if ( is_array($value) )
			{
				foreach ( $value as $k => $v )
				{
					
					$value[$k] = mysql_real_escape_string($value[$k]);
					$value[$k] = $prefix.$value[$k].$postfix;
				}

				$value = implode(',', $value);
				$value = '('.$value.')';
			}
			else
			{
				$value = mysql_real_escape_string($value);
				$value = $prefix.$value.$postfix;
			}

			if ( in_array($operator, $likes) )
			{
				$operator = 'LIKE';
			}

			$name = '`'.$name.'`';

			$conditions[] = $name.' '.$operator.' '.$value;
		}

		$condition = implode(' '.$this->andor.' ', $conditions);
		return $condition;
	}
}

?>
